package org.zsk.cs.util.common.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

/**
 * 数组类型转换器
 * @author zsk
 * @version 1.0
 * Create on 2019/11/14
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(value= List.class)
public class ListToStringTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int idx, List<String> list, JdbcType jdbcType) throws SQLException {
        ps.setString(idx,list.toString());
    }

    // 通过列名读取性别
    @Override
    public List<String> getNullableResult(ResultSet rs, String col)
            throws SQLException {
        String community=rs.getString(col);
        if (StringUtils.hasText(community)){
            return Arrays.asList(community
                    .substring(1,community.length()-1)
                    .split(", "));
        }
        return null;
    }

    // 通过下标读取性别
    @Override
    public List<String> getNullableResult(ResultSet rs, int idx)
            throws SQLException {
        String community=rs.getString(idx);
        if (StringUtils.hasText(community)){
            return Arrays.asList(community
                    .substring(1,community.length()-1)
                    .split(", "));
        }
        return null;
    }


    // 通过存储过程读取性别
    @Override
    public List<String> getNullableResult(CallableStatement cs, int idx)
            throws SQLException {
        String community=cs.getString(idx);
        if (StringUtils.hasText(community)){
            return Arrays.asList(community
                    .substring(1,community.length()-1)
                    .split(", "));
        }
        return null;
    }

}